<?php
namespace Home\Controller;
use Think\Controller;
class CustomerController extends CommonController {
    public function index(){
    	//p($_SERVER);
    	//p( I('uid'));
        $this->display();
    }

    public function logout(){
        session('uid',null); 
        session_unset();
        session_destroy();
        $this->redirect('Index/index');//, 0, 1, '');
    }
    public function addCustomer(){
        //echo "11";
        if($ulevel>99){
            echo "<script>alert('管理员无功能，请用客服ID添加客户');history.back(-1);</script>";
            die;
        }

        //echo "22";
        $this->display('addCustomer');
        //echo "33";
    }
    public function addCustomerDo(){
    	if(!IS_POST) $this->error('非法请求');
    	//p(I('post.'));
    	//p(I('post.tel','','htmlspecialchars')); 采用htmlspecialchars方法对$_POST['name'] 进行过滤，如果不存在则返回空字符串
    	//I方法的所有获取变量如果没有设置过滤方法的话都会进行htmlspecialchars过滤
		// I('get.name'); 等同于 htmlspecialchars($_GET['name'])
    	//p(I('post.tel'));    	 
    	//p($_POST('tel'));
    	$data = array(
    		'tel'=>I('post.tel'),
    		'name'=>I('post.name'),
    		'email'=>I('post.email'),
    		'level'=>I('post.level'),
    		'remark'=>I('post.remark'),
            'addip' => get_client_ip(),
    		'addtime' => date("YmdHis")
    		);
    	$id = M('customer_info')->data($data)->add();
    	if($id>0){
    		//echo "<script>alert('insert OK');</script>";
            $this->redirect('Customer/addCustomer', 0, 1, 'insert OK');
    	}
        else{
            echo "<script>alert('insert Error');history.back(-1);</script>";
        }
    	//M('customer_info')->where("id=%d and username='%s' and xx='%f'",$id,$username,$xx)->select();
    	//echo $id;
    	//echo "<script>alert(111);</script>";
    	//$this->success('新增成功', 'addCustomer');
    	$this->display('addCustomer');
    }
    public function editCustomer($id=0){
        //if(!IS_POST) $this->error('非法请求');
        //p(I('get.id'));
        //echo 'id='.$id;
        $uid = session('uid');
        $ulevel = session('ulevel');

        if($ulevel>99){
            $data=M('customer_info')->where("id=%d",$id)->select();
        }else{
            $data=M('customer_info')->where("uid='%s' and id=%d",$uid,$id)->select();
        }

        //p($data);

        $this->assign('data',$data[0]);// 赋值数据集
        $this->display(); // 输出模板
    }
    public function editCustomerDo(){
        if(!IS_POST) $this->error('非法请求');
        //p(I('post.'));
        $uid = session('uid');
        $ulevel = session('ulevel');

        //p(I('post.id'));
        $id=I('post.id');
        //echo $id;
        $data = array(
        'tel'=>I('post.tel'),
        'name'=>I('post.name'),
        'email'=>I('post.email'),
        'baduki'=>I('post.baduki'),
        'toto'=>I('post.toto'),
        'baccart'=>I('post.baccart'),
        'level'=>I('post.level'),
        'remark'=>I('post.remark')
         //'addtime' => date("YmdHis")
        );
        if($ulevel>99){
            $id = M('customer_info')->where("id=%d",$id)->setField($data);
        }else{
            $id = M('customer_info')->where("uid='%s' and id=%d",$uid,$id)->setField($data);
        }
        //echo $id;
        if($id>0){
            //echo "<script>alert('edit OK');history.back(-1);</script>";
            $this->success('OK','',0);//等待时间为0无效
        }
    }
    public function callCustomer($id=0){
        //if(!IS_POST) $this->error('非法请求');
        //p(I('get.id'));
        //echo 'id='.$id;
        $uid = session('uid');
        $ulevel = session('ulevel');

        if($ulevel>99){
            //$data=M('customer_info')->where("id=%d",$id)->select();
            $list=M('customer_call_log')->where("cid=%d",$id)->order('addtime DESC')->limit(20)->select();
            $customer=M('customer_info')->where("id=%d",$id)->order('addtime DESC')->find();
            $user=M('user_info')->where("uid=%s",$customer['uid'])->order('addtime DESC')->find();
            $data=M('customer_info')->where("id=%d",$id)->select();
            //只有客服才能添加记录
            //die;
        }else{
            $data=M('customer_info')->where("uid='%s' and id=%d",$uid,$id)->select();
            $list=M('customer_call_log')->where("uid='%s' and cid=%d",$uid,$id)->order('addtime DESC')->limit(20)->select();
        }

        //p($data);
        //echo $ulevel;
        $this->assign('user',$user);// 赋值数据集
        $this->assign('ulevel',$ulevel);// 赋值数据集
        $this->assign('data',$data[0]);// 赋值数据集
        $this->assign('list',$list);// 赋值数据集
        $this->display(callCustomer); // 输出模板
    }
    public function callCustomerDo(){
        if(!IS_POST) $this->error('非法请求');
        $uid = session('uid');
        $ulevel = session('ulevel');

        //p(I('post.id'));
        $id=I('post.id');
        //echo $id;
        $data = array(
        'uid'=>$uid,
        'cid'=>$id,
        'tel'=>I('post.tel'),
        'name'=>I('post.name'),
        'log'=>I('post.log'),
        'addip' => get_client_ip(),
        'addtime' => date("YmdHis")
        );
        $data2 = array(
        'lastip' => get_client_ip(),
        'lasttime' => date("YmdHis")
        );
        if($ulevel>99){
            //$id = M('customer_info')->where("id=%d",$id)->setField($data);
            //只有客服才能添加记录
            die;
        }else{
            $reid = M('customer_call_log')->data($data)->add();
            $reid = M('customer_info')->where("uid='%s' and id=%d",$uid,$id)->setField($data2);
        }
        //echo $reid;
        if($reid>0){
            //echo "<script>alert('add OK');window.location.reload(true); </script>";
            $this->assign('waitSecond',0);//等待时间为0无效
            $this->success('OK','',0);//等待时间为0无效
            //$this->redirect;
        }
    }

    public function showCustomerList($tel="",$kfid="",$dt1="",$dt2="",$level="",$astime="", $baduki="",$toto="",$baccart=""){
        //p(I('get.'));
        //echo "$dt1 :" .$dt1;
	    /*	
	    $re=M('customer_info')->where("uid='%s'",$uid)->order('addtime DESC')->select();
	    $this->assign('list',$re);	
	    $this->display();
	    */
        $uid = session('uid');
        $ulevel = session('ulevel');
	    $User = M('customer_info'); // 实例化User对象
		// 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
        if($ulevel>99){
            if($kfid<>""){
                //echo "kfid";
                $where['uid'] = $kfid;
            }
            if($dt1<>"" || $dt2<>""){
                //echo "dt1";
                //$where['lasttime']  = array('EGT',$dt1);//大于等于
                //$where['lasttime']  = array('ELT',$dt2);//小于等于
                $where['lasttime']  = array(array('EGT',$dt1),array('ELT',$dt2),"and");//
            }
            if($level<>""){
                $where['level']  = $level;//
            }
            if($baduki<>""){$where['baduki']  = 1;}
            if($toto<>""){$where['toto']  = 1;}
            if($baccart<>""){$where['baccart']  = 1;}
            if($tel<>""){$where['tel']  = $tel;}
            //p( $where);
            if($astime==1){$order='addtime DESC';}
            if($astime==2){$order='lasttime DESC';}
            //p( $order);  
            $list = $User->where($where)->order($order)->page($_GET['p'].',30')->select();
            $count= $User->where($where)->count();// 查询满足要求的总记录数

            $userlist=M('user_info')->field('uid,uname')->order('addtime DESC')->select();

        }
        //echo $this->outid;
        //echo $userlist;
		$Page       = new \Think\Page($count,30);// 实例化分页类 传入总记录数和每页显示的记录数
		//$Page->setConfig('header','<span class="rows">共 $count 条记录</span>');
		$show       = $Page->show();// 分页显示输出


		//$list = $User->where("uid='%s'",$uid)->order('addtime DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('kfid',$kfid);// 赋值数据集
        $this->assign('userlist',$userlist);// 赋值数据集
        $this->assign('list',$list);// 赋值数据集
		$this->assign('page',$show);// 赋值分页输出

		//分页跳转的时候保证查询条件
		// foreach($map as $key=>$val) {
		//     $Page->parameter[$key]   =   urlencode($val);
		// }
		$this->display(); // 输出模板
    }
    public function changeCustomerOwner(){
        //p(I('post.'));
        //p(I('post.tel'));
        $ulevel = session('ulevel');//修改者的级别
        if($ulevel<100){
            die();
        }

        $ownid=I('post.ownid');
        $tel=I('post.tel');
        foreach ($tel as $key=>$value)
        {
            //echo $key.':'.$value;
            $data = array(
            'uid'=>$ownid
            );
            $id = M('customer_info')->where("tel=%s",$value)->setField($data);
        }
        //echo $id;
        $this->success('OK','',0);//等待时间为0无效
    }
    //******************************************下面是XLS****************************************
    public function downloadXLS(){
        //p(I('post.'));
        //p(I('post.tel'));
        $ulevel = session('ulevel');//修改者的级别
        if($ulevel<100){
            die();
        }
        $tel=I('post.tel');
        $i=0;
        foreach ($tel as $key=>$value)
        {
            //echo $key.':'.$value;
            $customer = M('customer_info')->field('uid,tel,name,email,level,baduki,toto,baccart,remark,lasttime,addtime')->where("tel=%s",$value)->find();
            $arr[$i]=$customer;
            $i++;
        }
        //p($arr);
        $file_name = date('Ymd', time()).'_'.'customer';    
        exportexcel($arr,array('uid','tel','name','email','level','baduki','toto','baccart','remark','lasttime','addtime'),$file_name);
    }
    public function downloadAllXLS($tel="",$kfid="",$dt1="",$dt2="",$level="",$astime="", $baduki="",$toto="",$baccart=""){
        //p(I('get.'));
        //echo "level :" .$level;

        $uid = session('uid');
        $ulevel = session('ulevel');
        // 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
        if($ulevel>99){
            if($kfid<>""){
                //echo "kfid";
                $where['uid'] = $kfid;
            }
            if($dt1<>"" || $dt2<>""){
                //echo "dt1";
                //$where['lasttime']  = array('EGT',$dt1);//大于等于
                //$where['lasttime']  = array('ELT',$dt2);//小于等于
                $where['lasttime']  = array(array('EGT',$dt1),array('ELT',$dt2),"and");//
            }
            if($level<>""){
                $where['level']  = $level;//
            }
            if($baduki<>""){$where['baduki']  = 1;}
            if($toto<>""){$where['toto']  = 1;}
            if($baccart<>""){$where['baccart']  = 1;}
            if($tel<>""){$where['tel']  = $tel;}
            //p( $where);
            if($astime==1){$order='addtime DESC';}
            if($astime==2){$order='lasttime DESC';}
            //p( $order);  
            $list = M('customer_info')->field('uid,tel,name,email,level,baduki,toto,baccart,remark,lasttime,addtime')->where($where)->order($order)->select();
            $file_name = date('Ymd', time()).'_'.'customer';    
            exportexcel($list,array('uid','tel','name','email','level','baduki','toto','baccart','remark','lasttime','addtime'),$file_name);
        }

    }
    public function deleteSeletcCustomer(){
        p(I('post.'));
        //p(I('post.tel'));
        $ulevel = session('ulevel');//修改者的级别
        if($ulevel<100){
            die();
        }
        $tel=I('post.tel');
        $i=0;
        foreach ($tel as $key=>$value)
        {
            //echo $key.':'.$value;
            $customer = M('customer_info')->where("tel=%s",$value)->delete();
            //$arr[$i]=$customer;
            $i++;
        }
        //echo "<script>alert('delete OK');</script>";
        //$this->redirect('Home/Customer/showCustomerList/p/1');//, 0, 1, '');
        $this->success('OK','',0);//等待时间为0无效
    }
    public function uploadCustomer(){
        $this->display();
    }
    public function uploadCustomerDo(){
        if(!IS_POST) $this->error('非法请求');
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('xls', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =      './Uploads/'; // 设置附件上传根目录
        //$upload->savePath  =      ''; // 设置附件上传（子）目录
        $upload->saveName  =  date ( 'Ymdhis' );
        // 上传文件 
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        }else{// 上传成功 获取上传文件信息
            foreach($info as $file){
                //echo $file['savepath'].$file['savename'];
            }
        }


        vendor('PHPExcel');
         $PHPExcel = new \PHPExcel();
         $saveFile = './Uploads/' .$file['savepath'].$file['savename'];
         //$saveFile = './Uploads/11.xls' ;
         //$saveFile="D:/360disk/www/crmadmin/Uploads/12.xls";
         //echo $saveFile;
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        //为了可以读取所有版本Excel文件
        if(!$PHPReader->canRead($saveFile))
        {                       
            $PHPReader = new \PHPExcel_Reader_Excel5();  
            if(!$PHPReader->canRead($saveFile))
            {                       
                echo '未发现Excel文件或文件格式不正确！';
                return;
            }
        }
        //不需要读取整个Excel文件而获取所有工作表数组的函数，感觉这个函数很有用，找了半天才找到
        $sheetNames  = $PHPReader->listWorksheetNames($saveFile);
        //读取Excel文件
        $PHPExcel = $PHPReader->load($saveFile);
        //获取工作表的数目
        $sheetCount = $PHPExcel->getSheetCount();
        //选择第一个工作表
        $currentSheet = $PHPExcel->getSheet(0);
        //取得一共有多少列
        $allColumn = $currentSheet->getHighestColumn();   
        //取得一共有多少行
        $allRow = $currentSheet->getHighestRow();  
 
        $flg=0;
        //echo $currentSheet->getCell('A2')->getValue();
        if($currentSheet->getCell('A1')->getValue()=="uid" && $currentSheet->getCell('B1')->getValue()=="tel" && $currentSheet->getCell('F1')->getValue()=="baduki"){
             //循环读取数据，默认编码是utf8，这里转换成gbk输出
            for($currentRow = 2;$currentRow<=$allRow;$currentRow++)
            {
                    //echo $address . "#";
                    //echo iconv( 'utf-8','gbk', $currentSheet->getCell($address)->getValue() )."\t";
                    //echo  $currentSheet->getCell($address)->getValue() ."\t";
                    $data = array(
                    'uid'=>$currentSheet->getCell('A'.$currentRow)->getValue(),
                    'tel'=>$currentSheet->getCell('B'.$currentRow)->getValue(),
                    'name'=>$currentSheet->getCell('C'.$currentRow)->getValue(),
                    'email'=>$currentSheet->getCell('D'.$currentRow)->getValue(),
                    'level'=>$currentSheet->getCell('E'.$currentRow)->getValue(),
                    'baduki'=>$currentSheet->getCell('F'.$currentRow)->getValue(),
                    'toto'=>$currentSheet->getCell('G'.$currentRow)->getValue(),
                    'baccart'=>$currentSheet->getCell('H'.$currentRow)->getValue(),                  
                    'remark'=>$currentSheet->getCell('B'.$currentRow)->getValue(),
                    'addip' => get_client_ip(),
                    'addtime' => date("YmdHis")
                    );
                    $id = M('customer_info')->data($data)->add();
            }
            $this->success('OK','',0);//等待时间为0无效 
        }else{
            echo 'Excel文件格式不正确！';
            return;
        }



    }

    //******************************************下面是user****************************************
    public function deleteUser($kfid=""){
        //p(I('get.'));
        //echo "kfid=" . $kfid ."#";
        $ulevel = session('ulevel');//修改者的级别
        if($ulevel>99){
            if($kfid<>""){
                //echo "111";
                $where['uid'] = $kfid;
                $re = M('user_info')->where($where)->delete();

                //echo "re=" . $re. "#";
            }
            if($re>0){
                $this->success('delete OK','',0);//等待时间为0无效
            }
        }
    }
    public function showUserList(){
        /*  
        $re=M('customer_info')->where("uid='%s'",$uid)->order('addtime DESC')->select();
        $this->assign('list',$re);  
        $this->display();
        */
        $uid = session('uid');
        $ulevel = session('ulevel');
        $User = M('user_info'); // 实例化User对象
        //echo "display1";
        // 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
        if($ulevel>99){
            $list = $User->where()->order('addtime DESC')->page($_GET['p'].',15')->select();
            $count      = $User->where()->count();// 查询满足要求的总记录数
        }else{
        }

        //echo $this->outid;
        //echo $uid;
        $Page       = new \Think\Page($count,15);// 实例化分页类 传入总记录数和每页显示的记录数
        //$Page->setConfig('header','<span class="rows">共 $count 条记录</span>');
        $show       = $Page->show();// 分页显示输出


        //$list = $User->where("uid='%s'",$uid)->order('addtime DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('list',$list);// 赋值数据集
        $this->assign('page',$show);// 赋值分页输出

        //分页跳转的时候保证查询条件
        // foreach($map as $key=>$val) {
        //     $Page->parameter[$key]   =   urlencode($val);
        // }
        //echo "display2";
        $this->display(); // 输出模板
    }
    public function changeUserLevelDo(){
        if(!IS_POST) $this->error('非法请求');
        //$uid = session('uid');
        $ulevel = session('ulevel');//修改者的级别

        //p(I('post.id'));
        //$id=I('post.id');
        //echo $id;
        $data = array(
        //'id'=>I('post.id'),
        'ulevel'=>I('post.ulevel'),//被修改者的级别
         //'addtime' => date("YmdHis")
        );
        if($ulevel>99){
            $id = M('user_info')->where("id=%d",I('post.id'))->setField($data);
        }else{
            //恶意修改 应写入日志
            //$id = M('customer_info')->where("uid='%s' and id=%d",$uid,$id)->setField($data);
        }
        echo $id;
        if($id>0){
            //echo "<script>alert('edit OK');history.back(-1);</script>";
            //$this->success('操作完成');
            $this->redirect('Home/Customer/showUserList/p/1');//, 0, 1, '');
        }
    }    
}